<template>
  <canvas ref="canvas" class="fit overflow-hidden"></canvas>
  <q-resize-observer @resize="onResize"></q-resize-observer>
</template>

<script setup>
import { MapControls } from 'three/addons'
import { onMounted, ref } from 'vue'
import * as THREE from 'three'

let scene = null, camera = null, renderer = null, controls = null
const canvas = ref(null)
const screenSize = ref({ width: 0, height: 0 })
const initCanvas = () => {
  scene = new THREE.Scene();
  scene.background = new THREE.Color(0xcccccc);
  scene.fog = new THREE.FogExp2(0xcccccc, 0.001);

  renderer = new THREE.WebGLRenderer({ canvas: canvas.value, antialias: true, alpha: true })
  renderer.setSize(screenSize.value.width, screenSize.value.height)
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setAnimationLoop(animate);

  camera = new THREE.PerspectiveCamera(60, screenSize.value.width / screenSize.value.height, 1, 1000);
  camera.position.set(0, 200, -400);

  // controls

  controls = new MapControls(camera, renderer.domElement);

  //controls.addEventListener( 'change', render ); // call this only in static scenes (i.e., if there is no animation loop)

  controls.enableDamping = true; // an animation loop is required when either damping or auto-rotation are enabled
  controls.dampingFactor = 0.05;

  controls.screenSpacePanning = false;

  controls.minDistance = 50;
  controls.maxDistance = 1000;

  controls.maxPolarAngle = Math.PI / 2;

  // world

  const geometry = new THREE.BoxGeometry();
  geometry.translate(0, 0.5, 0);
  const material = new THREE.MeshPhongMaterial({ color: 0xeeeeee, flatShading: true });

  for (let i = 0; i < 500; i++) {

    const mesh = new THREE.Mesh(geometry, material);
    mesh.position.x = Math.random() * 1600 - 800;
    mesh.position.y = 0;
    mesh.position.z = Math.random() * 1600 - 800;
    mesh.scale.x = 20;
    mesh.scale.y = 20
    mesh.scale.z = 20;
    mesh.updateMatrix();
    mesh.matrixAutoUpdate = false;
    scene.add(mesh);

  }

  // lights

  const dirLight1 = new THREE.DirectionalLight(0xffffff, 3);
  dirLight1.position.set(1, 1, 1);
  scene.add(dirLight1);
  //
  const dirLight2 = new THREE.DirectionalLight(0x002288, 3);
  dirLight2.position.set(-1, -1, -1);
  scene.add(dirLight2);
  //
  const ambientLight = new THREE.AmbientLight(0x555555);
  scene.add(ambientLight);
  (controls)
  controls.zoomToCursor = true
}
const animate = () => {
  // requestAnimationFrame(animate)
  controls.update()
  renderer.render(scene, camera)
}
const onResize = (size) => {
  screenSize.value = size
  if (!camera) return
  camera.aspect = size.width / size.height
  camera.updateProjectionMatrix()
  renderer && renderer.setSize(size.width, size.height)
}
onMounted(initCanvas)
</script>